package com.itic.mall.mobile.pay;


import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.XmltoJsonUtil;
import com.itic.appbase.framework.utils.wxpay.WeixinPayUtil;
import com.itic.appbase.framework.utils.wxpay.vo.PayMsgVo;
import com.itic.appbase.framework.utils.wxpay.vo.WxpayConfig;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.service.OrderService;
import com.itic.mall.system.user.persistence.model.MallUser;

import net.sf.json.JSONObject;


@Controller
@RequestMapping(value="/mobile/weixin")
public class WeixinPay
     extends BaseMobileInterface {
	
	@Autowired
	private OrderService orderService;
	
	//微信异步通知  
	@RequestMapping(value = "/libin")   
	@ResponseBody 
    public void libin(String id){
         Order order = orderService.get(id);
		 if(  "0".equals(order.getStatus()) ){ 
			//处理自己的业务逻辑  
			paySuccess(order,"微信APP支付");
			
		 }
    }
	
	//微信异步通知  
	@RequestMapping(value = "/success")   
	@ResponseBody 
	public void notify(HttpServletRequest request,HttpServletResponse response) throws Exception{  
	    request.setCharacterEncoding("UTF-8");  
	    response.setCharacterEncoding("UTF-8");  
	    response.setContentType("text/html;charset=UTF-8");  
	    response.setHeader("Access-Control-Allow-Origin", "*");   
	    InputStream in=request.getInputStream();  
	    ByteArrayOutputStream out=new ByteArrayOutputStream();  
	    byte[] buffer =new byte[1024];  
	    int len=0;  
	    while((len=in.read(buffer))!=-1){  
	        out.write(buffer, 0, len);  
	    }  
	    out.close();  
	    in.close();  
	    String msgxml=new String(out.toByteArray(),"utf-8");//xml数据  
	    System.out.println(msgxml); 
	    String xml2json = XmltoJsonUtil.xml2JSON(msgxml);
	    
	    JSONObject fromObject = JSONObject.fromObject(xml2json);
		JSONObject jsonObject = fromObject.getJSONObject("xml");
		
		 String result_code = jsonObject.getJSONArray("result_code").get(0).toString();
		 String return_code = jsonObject.getJSONArray("return_code").get(0).toString();
		 
		 String out_trade_no  = jsonObject.getJSONArray("out_trade_no").get(0).toString(); 
		 Order order = orderService.get(out_trade_no);
		 
		 if( result_code.equals("SUCCESS") && return_code.equals("SUCCESS") && null != order && "0".equals(order.getStatus()) ){ 
				/* String appid  = jsonObject.getJSONArray("appid").get(0).toString();  
				 String back_type  = jsonObject.getJSONArray("bank_type").get(0).toString();  
				 String cash_fee  = jsonObject.getJSONArray("cash_fee").get(0).toString();  
				 String fee_type  = jsonObject.getJSONArray("fee_type").get(0).toString();  
				 String is_subscribe  = jsonObject.getJSONArray("is_subscribe").get(0).toString();  
				 String mch_id  = jsonObject.getJSONArray("mch_id").get(0).toString();  
				 String nonce_str  = jsonObject.getJSONArray("nonce_str").get(0).toString();  
				 String openid  = jsonObject.getJSONArray("openid").get(0).toString();  
				 
				 //String out_trade_no  = jsonObject.get("out_trade_no").toString();  
				 String sign  = jsonObject.getJSONArray("sign").get(0).toString();  
				 String time_end  = jsonObject.getJSONArray("time_end").get(0).toString();  
				 String total_fee  = jsonObject.getJSONArray("total_fee").get(0).toString();  
				 String trade_type  = jsonObject.getJSONArray("trade_type").get(0).toString();  
				 String transaction_id  = jsonObject.getJSONArray("transaction_id").get(0).toString(); 
				 
				 //生成签名
				 SortedMap<Object,Object> parameters = new TreeMap<Object,Object>(); 
				 parameters.put("appid", appid);
				 parameters.put("back_type", back_type);
				 parameters.put("cash_fee", cash_fee);
				 parameters.put("fee_type", fee_type);
				 parameters.put("is_subscribe", is_subscribe);
				 parameters.put("mch_id", mch_id);
				 parameters.put("nonce_str", nonce_str);
				 parameters.put("openid", openid);
				 parameters.put("out_trade_no", out_trade_no);
				 parameters.put("time_end", time_end);
				 parameters.put("total_fee", total_fee);
				 parameters.put("trade_type", trade_type);
				 parameters.put("transaction_id", transaction_id);
				 parameters.put("result_code", result_code);
				 parameters.put("return_code", return_code);
				
				 WeixinpayConfig weixinpayConfig = new WeixinpayConfig();
				 String sign2 = createSign("UTF-8",weixinpayConfig.getSecret(),parameters);
				 if( sign.equals(sign2) ){
					  
				 }*/
			 
			  try{  
                 //处理自己的业务逻辑  
				 String result = paySuccess(order,"微信APP支付");
                 response.getWriter().write(setXml(result, "OK"));    //告诉微信已经收到通知了  
              }catch(Exception e){  
            	  logException("WeixinPay", "pay", e.toString(),"微信APP支付",e);
              } 
			 
		 }else{
			 response.getWriter().write(setXml("SUCCESS", "OK"));    //告诉微信已经收到通知了  
		 }
		
	}  
	    
	
	public String getMoney( String money ){
		String ttmp =  NumberStringHelper.mulString(money, "100");
		double temp = Double.parseDouble(ttmp);
		Integer tmp =(int)temp;
		return tmp+"";
	}
	
	
	@RequestMapping(value="pay")
	@ResponseBody
	public Map<String,Object> pay( HttpServletRequest request,HttpServletResponse response, String token,String orderId ){
		String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		DataInputStream input = null;   
		  
		java.io.ByteArrayOutputStream out = null;   
		
		try{
			if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(orderId) ){
				MallUser user = getMallUserByToken(token);
				if( null != user ){
					Order order = verifyOrder(user.getId(),orderId);
					
					if( null != order ){
						//验证订单
						//Order order = verifyOrder(user.getId(),orderNum);
						PayMsgVo payVo = new PayMsgVo();
						payVo.setDesc("友惠家商城");
						payVo.setOrderNum(order.getId());
						payVo.setTotalMoney(order.getTotalMoney());
				        Map<String, Object> jsonPay = WeixinPayUtil.pay(request, new WxpayConfig(),payVo);
						 
				        resultMap.put(DATA, jsonPay);
				        
				        result = SUCCESS;
						errorCode = SUCCESS_ERROR_CODE;
				    	errorMsg = SUCCESS_ERROR_MSG;
					}else{
						result = FAIL;
						errorCode = ORDER_NULL_ERROR_CODE;
				    	errorMsg = ORDER_NULL_ERROR_MSG;
					}
				}else{
					result = LOGIN;
					errorCode = LOGIN_ERROR_CODE;
			    	errorMsg = LOGIN_ERROR_MSG;
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("WeixinPay", "pay", e.toString(),"微信APP支付",e);
		}finally{
			if( null != input ){
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if( null != out ){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	
	
	/**
	 * 验证订单方法
	 * @param payType
	 * @param orderNum
	 * @return
	 */
	public Order verifyOrder(String userId,String orderId){
		Order order = null;
	    order = orderService.get(orderId);
		//订单是否已支付，订单是否为用户的
		if( null != order ){
			String userId2 = order.getUserId();
			if( userId.equals(userId2) ){
				if( !order.getStatus().equals("0") ){
					order = null;
				}
			}else{
				order = null;
			}
		}
		return order;
		
	}
	
	
	public static String setXml(String return_code,String return_msg){  
        return "<xml><return_code><![CDATA["+return_code+"]]></return_code><return_msg><![CDATA["+return_msg+"]]></return_msg></xml>";  
    }  
	
}